package com.shiger.pingworld;

import android.os.AsyncTask;
import android.util.Log;

import java.util.ArrayList;

/**
 * created by shiger on 11/12/18.
 */

public class Model {

    private String TAG = Model.class.getSimpleName();
    private ArrayList<String> mPingList = new ArrayList<String>();

    private ArrayList<LoadPingTask> mPingTaskList = new ArrayList<LoadPingTask>();
    private final int Ping_Count = 1;
    private static Model sInstance;

    public synchronized static Model getInstance() {
        if (sInstance == null) {
            sInstance = new Model();
        }
        return sInstance;
    }


    public void loadPingResult(String url, OnPingFinishedLister pingFinishedLister) {
        LoadPingTask loadPingTask = new LoadPingTask(url, pingFinishedLister);
        int index = mPingTaskList.indexOf(loadPingTask);
        if (index != -1) {
            LoadPingTask task = mPingTaskList.get(index);
            task.cancel(true);
            mPingTaskList.remove(index);
        }
        mPingTaskList.add(loadPingTask);
        loadPingTask.execute();
    }
    
    //
    private class LoadPingTask extends AsyncTask<String, Void, String> {
        private String mUrl;
        private OnPingFinishedLister mPingFinishedLister;

        public LoadPingTask(String url, OnPingFinishedLister pingFinishedLister) {
            this.mUrl = url;
            this.mPingFinishedLister = pingFinishedLister;
        }

        @Override
        protected String doInBackground(String... params) {
            if (isCancelled()) {
                return null;
            } else {
                PingUtils pingUtils = new PingUtils();
                String pingResult = pingUtils.isPingSuccess(Ping_Count, mUrl);
                Log.d(TAG, "doInBackground: pingResult = " + pingResult);
                String pingAverage = pingUtils.extractNumAverage(pingResult);
                return pingAverage;
            }
        }

        @Override
        protected void onPostExecute(String bitmap) {
            super.onPostExecute(bitmap);
            mPingFinishedLister.onPingFinished(bitmap);
            mPingTaskList.remove(this);
        }

        public String getUrl() {
            return mUrl;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj != null && obj.getClass() == this.getClass()) {
                LoadPingTask task = (LoadPingTask) obj;
                return mUrl.equals(task.getUrl());
            }
            return false;

        }
    }


    public interface OnPingFinishedLister {
        void onPingFinished(String result);
    }
}
